<template>
  <div>
    <Content title="字典" :subTitle="isNew?'新建':'编辑'" path="/dict">
      <div slot="body">
        <div style="padding-left: 20px">
          <p style="font-size: 20px">字典</p>
          <el-form :model="form" label-position="left" :rules="rules" ref="form" label-width="140px" class="dict-form">
            <el-form-item label="编码" prop="code" class="my-form-item">
              <el-input v-model="form.code"></el-input>
            </el-form-item>
            <el-form-item label="描述" prop="description" class="my-form-item">
              <el-input v-model="form.description"></el-input>
            </el-form-item>
            <p style="color: #606266">字典值</p>
            <el-table v-loading="loading"
                      :data="attributes"
                      stripe
                      :show-header="false"
                      style="width: 100%">
              <el-table-column type="expand">
                <template slot-scope="scope" v-if="scope.row.type != 1">
                  <el-form-item label="备注" label-width="70px" prop="comment">
                    <el-input v-model="scope.row.comment" type="textarea"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                prop=""
                label="属性名"
                width="220">
                <template slot-scope="scope" v-if="scope.row.type != 1">
                  <el-form-item label="属性名" label-width="70px" prop="key">
                    <el-input v-model="scope.row.key"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                prop=""
                label="属性值"
                width="220">
                <template slot-scope="scope" v-if="scope.row.type != 1">
                  <el-form-item label="属性值" prop="value" label-width="70px">
                    <el-input v-model="scope.row.value"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                prop="priority"
                label="排序"
                width="130">
                <template slot-scope="scope" v-if="scope.row.type != 1">
                  <el-form-item label="排序" prop="priority" label-width="50px">
                    <el-input v-model="scope.row.priority" type="number"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                prop=""
                align="center"
                label="操作"
                min-width="50">
                <template slot-scope="scope">
                  <template v-if="scope.row.type != 1">
                    <el-button
                      type="danger"
                      size="mini"
                      icon="el-icon-delete"
                      @click="handleDelete(scope.$index, scope.row)">删除
                    </el-button>
                  </template>
                  <template v-else>
                    <el-button
                      type="success"
                      size="mini"
                      icon="el-icon-circle-plus-outline"
                      @click="handleAdd(scope.$index, scope.row)">新增
                    </el-button>
                  </template>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </div>
      </div>
    </Content>
    <div style="padding: 15px">
      <router-link to="/dict">
        <el-button plain round type="info" icon="el-icon-back">返回</el-button>
      </router-link>
      <el-button plain type="primary" @click="submitForm('form')" icon="el-icon-circle-check">保存</el-button>
    </div>
  </div>
</template>

<script>
  import util from '../../utils/util'
  import {Dict} from '../../utils/resource'
  import {showSaveResponse, validFieldExists, validateForm, deleteConfirm} from '../../utils/element-helper'

  import Content from '../../components/Content.vue'


  export default {
    name: 'dictDetail',
    components: {
      Content,
    },
    data() {
      return {
        loading: false,
        isNew: true,
        initForm: [],
        attributes: [],
        form: {},
        defaultProps: {
          value: "id",
          label: 'name',
          children: 'children'
        },
        rules: {
          code: [
            {required: true, message: '编码不能为空', trigger: 'blur'},
            {
              validator: (rule, value, callback) => {
                validFieldExists(rule, value, callback, this.initForm[rule.field] != value || this.isNew, (rule, value) => Dict.exists(rule, value))
              }, trigger: 'blur'
            }
          ],
          description: [
            {required: true, message: '描述不能为空', trigger: 'blur'},
          ],
        },
      }
    },
    created() {
      let code = this.$route.params.code
      this.isNew = (code == 'new')
      if (!this.isNew) {
        this.loadDict()
      } else {
        this.attributes = [{
          type: 1
        }]
      }
    },
    computed: {},
    methods: {
      async loadDict() {
        let code = this.$route.params.code
        let res = await Dict.listByCode(code)
        if (res.data.length > 1) {
          let ar = []
          for (let i = 0; i < res.data.length; i++) {
            let data = res.data[i]
            ar.push({
              key: data.key,
              value: data.value,
              priority: data.priority,
              comment: data.comment,
              error: ""
            })
          }
          ar.push({
            type: 1
          })
          this.attributes = ar
          this.form = {
            id: res.data[0].id,
            code: res.data[0].code,
            description: res.data[0].description
          }
          this.initForm = {
            id: res.data[0].id,
            code: res.data[0].code,
            description: res.data[0].description
          }
        }
      },
      handleDelete(index, row) {
        //删除
        this.attributes.splice(index, 1)
      },
      handleAdd(index, row) {
        row.type = 0
        this.attributes.push({
          type: 1
        })
      },
      submitForm(formName) {
        return validateForm(this, formName, () => {
          let attrs = []
          for (let i = 0; i < this.attributes.length; i++) {
            let atttrbute = this.attributes[i]
            if (atttrbute.type != 1) {
              if(util.isNull(atttrbute.key)){
                this.$message({
                  type: 'error',
                  message: '字典属性名不能为空！'
                })
                return
              }
              if(util.isNull(atttrbute.value)){
                this.$message({
                  type: 'error',
                  message: '字典属性值不能为空！'
                })
                return
              }
              attrs.push(this.attributes[i])
            }
          }
          if(attrs.length ===0){
            this.$message({
              type: 'error',
              message: '字典值至少包含一条数据！'
            })
            return
          }
          this.form.attributes = attrs
          showSaveResponse(this, () => Dict.updateWithAttribute(this.form), (res) => this.$router.back())
        })
      },
    },
  };
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .dict-form {
    width: 90%;
  }

  .el-form-item {
    margin-bottom: 0px;
  }

  .my-form-item {
    max-width: 600px;
    margin-bottom: 25px;
  }
</style>
